import React, {forwardRef, useRef} from 'react';
import {bindActionCreators} from 'redux';
import * as orderFormActionCreator from '../../actions/order-form-actions';
import {connect} from 'react-redux';
import {
  Dimensions,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {formatDate, getRealSize, SummaryParams, Touchable} from '../../utils';
import ThemeStyles from '../../styles';
import {OrderState} from '../../reducers/order-list';
import _ from 'lodash';
import Button from '../../components/button';
import Icon from 'react-native-vector-icons/FontAwesome';
import {SvgUri} from 'react-native-svg';
import {v4 as uuidv4} from 'uuid';
import Toast from '../../components/toast';
import Validator from 'async-validator';
import {I18n} from '../../reducers/intl';

export const validator = new Validator({
  products: [
    {
      validator: (rule, value, callback) => {
        const products = Object.values(value);
        if (products.length) {
          return callback();
        }
        callback(new Error(I18n.t('form.validate.message.product')));
      },
    },
  ],
});

class ProductScreen extends React.PureComponent {
  static navigationOptions = ({navigation}) => ({
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
    title: I18n.t('page.title.create'),
    headerRight: () => (
      <Touchable onPress={() => navigation.goBack()}>
        <View
          style={[ThemeStyles.Layout.base.padding, {height: getRealSize(48)}]}>
          <Text style={[ThemeStyles.Front.base]}>
            {I18n.t('button.previous')}
          </Text>
        </View>
      </Touchable>
    ),
  });

  state = {
    editable: false,
    selectedProduct: [],
  };

  componentDidMount() {
    const {navigation, form} = this.props;
    // console.log(form);
    if (form.isNew) {
      navigation.navigate('ProductEditModal');
    }
  }

  onNext = async () => {
    const {navigation, form} = this.props;
    try {
      await validator.validate(form);
      navigation.navigate('OrderFormOther');
    } catch (e) {
      Toast.show(e.errors[0].message);
    }
  };

  onEditable = () => {
    const {editable, selectedProduct} = this.state;
    if (editable) {
      selectedProduct.forEach(pid =>
        this.props.orderFormActions.removeProduct(pid),
      );
    }
    this.setState({
      editable: !editable,
      selectedProduct: [],
    });
  };

  onMarkProduct = p => {
    let selected;
    if (this.state.selectedProduct.includes(p.pid)) {
      selected = this.state.selectedProduct.filter(sp => sp.pid === p.pid);
    } else {
      selected = [...this.state.selectedProduct, p.pid];
    }
    this.setState({
      selectedProduct: selected,
    });
  };

  onEditableProduct = p => {
    const {orderFormActions, navigation} = this.props;
    orderFormActions.updateForm({draft: {pid: uuidv4(), ...p}});
    navigation.navigate('ProductEditModal');
  };

  render() {
    const {form} = this.props;
    const products = Object.values(form.products); // 当前已经添加的产品
    return (
      <ScrollView>
        <View style={Styles.content}>
          <View style={Styles.header}>
            <Text style={Styles.title}>{I18n.t('form.label.product')}</Text>
            <Touchable onPress={this.onEditable}>
              <Text>
                {this.state.editable
                  ? I18n.t('button.delete')
                  : I18n.t('button.manage')}
              </Text>
            </Touchable>
          </View>
          <View style={Styles.productList}>
            {products.map(p => (
              <ProductCard
                key={p.pid}
                {...p}
                selected={this.state.selectedProduct.includes(p.pid)}
                onMark={() => this.onMarkProduct(p)}
                editable={this.state.editable}
                onEditable={() => this.onEditableProduct(p)}
              />
            ))}
            <ProductAdd onAddProduct={() => this.onEditableProduct({})} />
          </View>
        </View>
        <View style={Styles.content}>
          <View style={Styles.header}>
            <Text style={Styles.title}>{I18n.t('form.label.order.info')}</Text>
          </View>
          <StateCard {...form} />
        </View>
        <View style={Styles.actionButton}>
          <Button label={I18n.t('button.next')} onPress={this.onNext} />
        </View>
      </ScrollView>
    );
  }
}

const ProductAdd = props => (
  <Touchable
    style={{backgroundColor: 'white'}}
    onPress={() => props.onAddProduct()}>
    <View style={Styles.productAddBox}>
      <Text style={Styles.productAddLabel}>{I18n.t('button.addProduct')}</Text>
    </View>
  </Touchable>
);

const ProductCard = props => {
  return (
    <View style={Styles.productBox}>
      <Touchable onPress={() => props.onEditable()}>
        <View style={Styles.productContainer}>
          <View style={Styles.productThumbnail}>
            <SvgUri
              fill={ThemeStyles.Color.primary.color}
              uri={_.get(props, 'product.url', '')}
              width={72}
              height={72}
            />
          </View>
          <View style={Styles.productContent}>
            <Text style={Styles.productTitle}>{props.product.name}</Text>
            <Text style={Styles.productSummary} numberOfLines={2}>
              {SummaryParams(props)}
            </Text>
          </View>
        </View>
      </Touchable>
      {props.editable && (
        <Touchable onPress={() => props.onMark()}>
          <View style={Styles.productMask}>
            <View style={Styles.productSelected}>
              <Icon
                name={props.selected ? 'check-circle-o' : 'circle-thin'}
                size={18}
                color={
                  props.selected ? ThemeStyles.Color.primary.color : '#C7C7CC'
                }
              />
            </View>
          </View>
        </Touchable>
      )}
    </View>
  );
};

const StateCard = props => {
  return (
    <View style={Styles.stateCardContainer}>
      <View style={Styles.stateCardRow}>
        <StateBlock
          label={I18n.t('order.props.created')}
          value={formatDate(new Date())}
        />
        <StateBlock
          label={I18n.t('order.props.state')}
          value={OrderState.ORDERING}
        />
      </View>
      <View style={Styles.stateCardRow}>
        <StateBlock
          label={I18n.t('order.props.dentist')}
          value={_.get(props, 'buyer.clinic_name', '')}
        />
        <StateBlock
          label={I18n.t('order.props.technician')}
          value={_.get(props, 'seller.vendor_name', '')}
        />
      </View>
    </View>
  );
};

const StateBlock = props => {
  return (
    <View style={Styles.stateBlockContainer}>
      <Text style={Styles.stateBlockLabel}>{props.label}:</Text>
      <Text style={Styles.stateBlockValue}>{props.value}</Text>
    </View>
  );
};

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  form: state.orderForm,
});

const mapDispatchToProps = dispatch => ({
  orderFormActions: bindActionCreators(orderFormActionCreator, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(ProductScreen);

const Styles = StyleSheet.create({
  container: {},
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  productContainer: {
    flexDirection: 'row',
    padding: getRealSize(15),
  },
  productThumbnail: {},
  productContent: {
    marginLeft: getRealSize(15),
    flex: 1,
  },
  productTitle: {
    fontWeight: 'bold',
    color: '#333',
  },
  productSummary: {
    fontSize: getRealSize(12),
    fontWeight: '400',
    color: '#757575',
    marginTop: getRealSize(12),
  },
  productMask: {
    backgroundColor: 'rgba(0,0,0, 0.4)',
    position: 'absolute',
    height: getRealSize(108),
    borderRadius: getRealSize(8),
    flex: 1,
    width: Dimensions.get('screen').width - getRealSize(30),
  },
  productSelected: {
    position: 'relative',
    top: getRealSize(8),
    left: getRealSize(8),
  },
  productBox: {
    backgroundColor: '#F6F6F6',
    borderRadius: getRealSize(8),
    marginBottom: getRealSize(15),
  },
  productAddBox: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#F6F6F6',
    height: getRealSize(88),
    borderRadius: getRealSize(8),
  },
  productAddLabel: {
    fontSize: getRealSize(12),
    color: '#999',
    fontWeight: '400',
  },
  content: {
    paddingHorizontal: getRealSize(15),
  },
  productList: {},
  title: {
    fontSize: getRealSize(22),
    fontWeight: 'bold',
    marginTop: getRealSize(18),
    marginBottom: getRealSize(15),
  },
  stateCardContainer: {
    borderRadius: getRealSize(4),
    backgroundColor: '#f7f7f7',
    paddingHorizontal: getRealSize(20),
    paddingBottom: getRealSize(10),
  },
  stateCardRow: {
    flexDirection: 'row',
  },
  stateBlockContainer: {
    flex: 1,
    marginTop: getRealSize(15),
  },
  stateBlockLabel: {
    fontSize: getRealSize(12),
    fontWeight: '400',
    color: '#757575',
  },
  stateBlockValue: {
    fontSize: getRealSize(16),
    fontWeight: 'bold',
    color: '#333',
    marginVertical: getRealSize(12),
  },
  actionButton: {
    marginVertical: getRealSize(12),
    paddingHorizontal: getRealSize(15),
  },
});
